package org.elsa.fingobtb.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * HMACSHA256加签
 */
public class ApiAuth {

    static Logger logger = LoggerFactory.getLogger(ApiAuth.class);

    public static UToken apiAuth(String payload, String apiKey, String secret){
        UToken token = new UToken();
        String hash = HMACSHA256(payload.getBytes(),secret.getBytes()).toLowerCase();
        logger.info(String.format("\n Payload----------> %s <----------",payload));
        logger.info(String.format("\n Sign----------> %s <----------", hash));
        token.setAccess_key(apiKey);
        token.setSignature(hash);
        return token;
    }

    public static String HMACSHA256(byte[] data, byte[] key)
    {
        try  {
            SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            return byte2hex(mac.doFinal(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String byte2hex(byte[] b)
    {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }
}
